using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RFS.BizLogic.PaiShi.Accounting;
using ycx;

namespace RFS.Domain.PaiShi.WorkFlow
{
    public class ProblemClass : IProblem
    {
        public bool IsAny
        {
            get
            {
                if (isComplex)
                {
                    if (_children.Values.All(x => x.IsAny == false))
                        return false;
                    else
                    {
                        return true;
                    }
                }
                else
                {
                    return !string.IsNullOrEmpty(Message);
                }
            }
        }


        private bool isComplex
        {
            get => _children.Count > 0;
        }

        string _message;

        public string Message
        {
            get
            {
                if (isComplex)
                {
                    var i = 0;
                    var sb = new StringBuilder();
                    sb.AppendLine($"[{_children.Count}]个问题：");
                    foreach (var c in _children.Values)
                    {
                        sb.AppendLine($"    {++i} [{c.Level.ToString()}]{c.Message}");
                    }

                    return sb.ToString();
                }
                else
                    return _message;
            }
            protected set => _message = value;
        }


        public void AddSubProblem(string msg = "", string key = null, ProblemLevel level = ProblemLevel.严重)
        {
            key = string.IsNullOrEmpty(key) ? $"{msg.GetHashCode()}" : key;
            var p = new ProblemClass(msg, level);
            
            _children[key] = p;
        }

        private ProblemLevel _level= ProblemLevel.没问题 ;
        public ProblemLevel Level
        {
            get
            {
                if (isComplex)
                {
                   return _children.Values.Select(x => x.Level).Max();
                }
                else
                {
                    return  _level ;
                }
            }
        }


        ConcurrentDictionary<string, IProblem> _children = new ConcurrentDictionary<string, IProblem>();
        // private string {  = "";

        public ProblemClass(string msg = "", ProblemLevel level = ProblemLevel.没问题)
        {
            Message = msg;
            _level= level;
        }

        IEnumerable<IProblem> Children
        {
            get => _children.Values;
        }

        public static ProblemClass Of(string problem = "")
        {
            return new ProblemClass(problem);
        }
    }
}